<template>
  <div class="flex1 ml15">
    <div class="kva-form-search">
      <el-form class="search-form align-center flex" :inline="true" :model="queryParams" ref="searchForm">
        <el-form-item prop="keyword">
          <div  v-if="showAlert">
            <el-alert
                size="small"
                @close="handleAlertClose"
                :title="'选中了（' + selectIds.length + '）项数据'"
                type="success"
                show-icon
            />
          </div>
        </el-form-item>
        <el-form-item prop="keyword">
          <el-button type="success" icon="Open" :loading="upLoading" @click="handleBatchStatus('up')">批量通过</el-button>
        </el-form-item>
        <el-form-item prop="keyword">
          <el-button type="warning" icon="Open" :loading="downLoading" @click="handleBatchStatus('down')">批量禁止</el-button>
        </el-form-item>
        <el-form-item prop="keyword">
          <el-button type="danger" icon="close" :loading="delLoading" @click="handleBatchRemoves()">批量删除</el-button>
        </el-form-item>
        <el-form-item prop="keyword">
          <el-input v-model="queryParams.keyword" placeholder="文章标题、用户名、uuid" maxlength="100" clearable/>
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select
              v-model="queryParams.status"
              class="m-2"
              @change="handleSearch"
              placeholder="请选择启用状态"
              clearable>
            <el-option
                v-for="item in [
                    { value: 1, label: '通过' },
                    { value: 0, label: '未通过' }
                  ]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="Search" @click.prevent="handleSearch">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="Refresh" @click.prevent="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-container style="border-radius: 8px; margin-top: 10px; background: #fff">
      <el-main style="--el-main-padding: 10px">
          <el-table
              v-loading="tableLoading"
              ref="tableRef"
              border
              :data="tableData"
              @selection-change="handleSelectionChange"
              height="calc(100vh - 280px)" >
            <el-table-column type="selection" align="center" width="55" />
            <el-table-column  :label="'总数：' + total">
              <template v-slot="scope">
               <div class="data-list">
                   <div class="list-items">
                      <div class="flex align-center justify-space-between">
                        <h3> <span>{{ scope.$index + 1 }}</span>：<a :href="currentSystem.domain+'/download/detail/'+scope.row.id" target="_blank" class="fw"><strong>评论资源：</strong>{{ scope.row.title}}</a></h3>
                        <p class="mt5"><strong>评论用户：</strong>{{scope.row.username}} <strong class="ml20">评论时间：</strong>{{ formatTimeToStr(scope.row.createTime) }}</p>
                        <div class="flex align-center">
                          <div class="mr20">
                          <el-switch
                              v-model="scope.row.status"
                              @change="handleStatus(scope.row, 'status')"
                              :active-value="1"
                              active-text="通过"
                              inactive-text="禁止"
                              :inactive-value="0"
                          >
                          </el-switch></div>
                          <a :href="currentSystem.domain+'/download/detail/'+scope.row.id" target="_blank" class="fw"><el-button icon="Open" type="success"  @click.stop="handleDel(scope.row)">访问预览</el-button></a>
                        </div>
                        </div>
                      <div class="mt5">
                        <div class="fz16" v-html="scope.row.content"></div>
                        <div class="mt10">
                          <a href="javascript:void(0);" @click.prevent="handleReplyMain(scope.$index)" class="green">回复</a>
                          <a href="javascript:void(0);" @click.prevent="handleDel(scope.row)" class="red ml15">删除</a>
                        </div>
                        <div class="mt20 mb20" v-if="currentIndex == scope.$index && currentChildIndex==-1">
                          <el-input type="textarea" :placeholder="'请输入对作者：【'+scope.row.username+'】的评论：'" rows="6" v-model="commentContent"></el-input>
                          <el-button type="primary" icon="check" class="mt10">提交回复</el-button>
                          <el-button type="success" icon="check" class="mt10">提交回复&通知</el-button>
                          <el-button type="info" @click="handleCancleReply" icon="delete" class="mt10">取消回复</el-button>
                        </div>
                      </div>

                      <div class="data-child-box mt20" v-if="scope.row.children.records && scope.row.children.records.length > 0">
                        <div class="list-items" v-for="(item,index) in scope.row.children.records" :key="index">
                          <div class="flex align-center justify-space-between">
                            <h3> <span>{{ index + 1 }}</span>：<a :href="currentSystem.domain+'/download/detail/'+item.id" target="_blank" class="fw"><strong>评论资源：</strong>{{ scope.row.title}}</a></h3>
                            <p class="mt5"><strong>评论用户：</strong>{{item.username}} <strong class="ml20">评论时间：</strong>{{ formatTimeToStr(item.createTime) }}</p>
                            <el-switch
                                v-model="item.status"
                                @change="handleStatusReply(item, 'status')"
                                :active-value="1"
                                active-text="通过"
                                inactive-text="禁止"
                                :inactive-value="0"
                            >
                            </el-switch>
                          </div>
                          <div class="mt5">
                            <div class="fz16" v-html="item.content"></div>
                            <div class="mt10">
                              <a href="javascript:void(0);" @click.prevent="handleReplyChildren(scope.$index,index)" class="green">回复</a>
                              <a href="javascript:void(0);" @click.prevent="handleDelReply(item,scope.row.children)" class="red ml15">删除</a>
                            </div>
                            <div class="mt20 mb20" v-if="currentIndex == scope.$index && currentChildIndex==index">
                              <el-input type="textarea" :placeholder="'请输入对作者：【'+scope.row.username+'】的评论：'" rows="6" v-model="commentContent"></el-input>
                              <el-button type="primary" icon="check" class="mt10">提交回复</el-button>
                              <el-button type="success" icon="check" class="mt10">提交回复&通知</el-button>
                              <el-button type="info" @click="handleCancleReply" icon="delete" class="mt10">取消回复</el-button>
                            </div>
                          </div>
                        </div>
                        <div v-if="scope.row.children.total > scope.row.children.size">
                          <div class="mt10" v-if="scope.row.children.current < scope.row.children.pages" @click="handleLoadMore(scope.row.children,scope.row.id)"><a href="javascript:void(0);" class="green">查看更多({{scope.row.children.total}})</a></div>
                          <div class="mt10" v-else><a href="javascript:void(0);" class="green">加载完毕({{scope.row.children.total}})</a></div>
                        </div>
                      </div>
                   </div>
               </div>
              </template>
            </el-table-column>
          </el-table>
         <div class="kva-pagination-box center">
          <el-pagination
              :current-page="queryParams.pageNo"
              :page-size="queryParams.pageSize"
              :page-sizes="[100,150,200,300]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>
<script setup>
import {formatTimeToStr} from '@/utils/date.js'
import KVA from '@/utils/kva.js'
import {batchDowns, batchRemoves, batchUps, removeById, findPages, updateStatus} from '@/api/download/comment.js'
import {findPages as findReplyPages,removeById as removeByIdReply,updateStatus as updateStatusReply} from '@/api/download/comment_reply.js'
import { useUserStore } from '@/stores/users.js'
const userStore = useUserStore();
const currentSystem = computed(() => userStore.systemList?.filter(c => c.defaultFlag == 1)[0])
const emits = defineEmits(["load"])
// 搜索属性定义
const queryParams = reactive({
  pageNo: 1,
  pageSize: 30,
  status: '',
  keyword: '',
  opid: '',
  uuid:''
})

const currentIndex = ref(0)
const currentChildIndex = ref(-1)

const commentContent = ref("")
// 定义响应式得列表数据容器
const tableData = ref([])
const tableHeight = ref('calc(100vh - 280px)')
const tableLoading = ref(false)
const delLoading = ref(false)
const downLoading = ref(false)
const upLoading = ref(false)
const showAlert = ref(false)
const selectIds = ref([])
const selectOpIds = ref([])
const pages = ref(0)
const total = ref(0)
const searchForm = ref({})
const tableRef = ref({})

// 加载数据
const handleLodeData = async () => {
  tableLoading.value = true
  const resp = await findPages(queryParams)
  tableLoading.value = false
  tableData.value = resp.data.records
  total.value = resp.data.total * 1
  pages.value = resp.data.pages * 1
}

const handleLoadMore = async (page,parentId)=>{
  if(page.current==page.pages){
    KVA.error("加载完毕!")
    return;
  }
  page.current++
  const resp = await findReplyPages({pageNo:page.current,pageSize:page.size,parentId:parentId})
  if(page.current == 1) {
    page.records = resp.data.records
  }else{
    page.records = page.records.concat(resp.data.records)
  }
}

// 主评论回复
const handleReplyMain = (index)=>{
  if(currentIndex.value == index && currentChildIndex.value == -1)return;
  currentIndex.value = index
  currentChildIndex.value = -1
}

// 主评论回复
const handleCancleReply = ()=>{
  commentContent.value = ""
  currentIndex.value = -1
  currentChildIndex.value = -1
}

// 主评论回复
const handleReplyChildren = (index,cindex)=>{
  if(currentChildIndex.value == cindex && currentChildIndex.value == cindex)return;
  currentIndex.value = index
  currentChildIndex.value = cindex
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  handleLodeData()
}

// 重置
const handleReset = () => {
  queryParams.opid = "";
  searchForm.value.resetFields()
  emits("load")
  handleSearch()
}

// 分页size更改
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  handleLodeData()
}

// 分页pageNo更改
const handleCurrentChange = (pno) => {
  queryParams.pageNo = pno
  handleLodeData()
}

// 删除
const handleDel = (row) => {
  KVA.confirm('警告', '<strong>您确定要执行，子评论也会一并删除！</strong>', {icon: 'success'}).then(async () => {
    const opid = row.id
    await removeById(opid)
    KVA.notifySuccess('删除成功!')
    handleLodeData()
  })
}

// 删除子回复
const handleDelReply = (row,page) => {
  KVA.confirm('警告', '<strong>您确定要执行此次操作吗？</strong>', {icon: 'success'}).then(async () => {
    const opid = row.id
    const parentId = row.parentId
    await removeByIdReply(opid)
    KVA.notifySuccess('删除成功!')
    page.current = 0
    page.total --
    handleLoadMore(page,parentId)
  })
}

// 清空选择
const handleAlertClose = () => {
  showAlert.value = false
  tableRef.value.clearSelection()
}

/**
 * 选择删除的元素
 * @param rows
 */
const handleSelectionChange = (rows) => {
  selectIds.value = rows.map((c) => c.id)
  selectOpIds.value = rows.map((c) => c.socialId)
  showAlert.value = rows.length > 0
  tableHeight.value = rows.length > 0 ? 'calc(100vh - 355px)' : 'calc(100vh - 315px)'
}

/**
 * 批量删除
 */
const handleBatchRemoves = async () => {
  if (selectIds.value.length == 0) {
    KVA.warning('请选择一项进行操作!')
    return
  }
  KVA.confirm('警告', '<strong>您确定要执行【批量删除】吗？，一旦执行无法恢复！</strong>', {icon: 'success'}).then(
      async () => {
        delLoading.value = true
        await batchRemoves(selectIds.value.join(','), selectOpIds.value.join(','))
        delLoading.value = false
        KVA.notifySuccess('批量删除成功!')
        handleLodeData()
      }
  )
}

/**
 * 批量上下架
 */
const handleBatchStatus = async (field) => {
  if (selectIds.value.length == 0) {
    KVA.warning('请选择一项进行操作!')
    return
  }
  if (field == 'up') {
    upLoading.value = true
    await batchUps(selectIds.value.join(','), selectOpIds.value.join(','))
    upLoading.value = false
  } else {
    downLoading.value = true
    await batchDowns(selectIds.value.join(','), selectOpIds.value.join(','))
    downLoading.value = false
  }
  KVA.notifySuccess('执行成功!')
  handleLodeData()
}

// 更新状态
const handleStatus = async (row) => {
  await updateStatus(row.id, 'status', row.status)
  KVA.notifySuccess('操作成功!')
  handleLodeData()
}

// 更新状态
const handleStatusReply = async (row) => {
  await updateStatusReply(row.id, 'status', row.status)
  KVA.notifySuccess('操作成功!')
  handleLodeData()
}


const handleLodeDataComment = (opid)=>{
  queryParams.opid = opid;
  handleLodeData()
}

onMounted(()=>{
  handleLodeData()
})

defineExpose({
  handleLodeDataComment
})
</script>

<style scoped>
.data-list .list-items{border-radius: 8px;border:2px solid #eee;padding: 20px;margin-bottom: 15px;}
.data-list .list-items:hover{border:2px solid #67c23a;}
.data-list .list-items p{padding-top:5px;}
</style>